package com.yupi.yupao.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 线程池配置
 * 用于支持异步任务，包括登录后的异步缓存预热
 */
@Configuration
@EnableAsync
public class ThreadPoolConfig {

    /**
     * 核心线程池数量，方法: CPU核数 / (1 - 阻塞系数)
     * 例如8核CPU可以设置为20
     */
    private static final int CORE_POOL_SIZE = 8;
    
    /**
     * 最大线程池数量
     */
    private static final int MAX_POOL_SIZE = 16;
    
    /**
     * 缓冲队列大小
     */
    private static final int QUEUE_CAPACITY = 100;
    
    /**
     * 允许线程的空闲时间(单位：秒)
     */
    private static final int KEEP_ALIVE_SECONDS = 60;
    
    /**
     * 异步预热任务执行器
     */
    @Bean(name = "asyncTaskExecutor")
    public Executor asyncTaskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(CORE_POOL_SIZE);
        executor.setMaxPoolSize(MAX_POOL_SIZE);
        executor.setQueueCapacity(QUEUE_CAPACITY);
        executor.setKeepAliveSeconds(KEEP_ALIVE_SECONDS);
        executor.setThreadNamePrefix("Async-Cache-");
        
        // 线程池对拒绝任务的处理策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 初始化
        executor.initialize();
        return executor;
    }
} 